
package com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.utils.JsonUtils;
import com.huaweicloud.sdk.drs.v3.DrsClient;
import com.huaweicloud.sdk.drs.v3.model.BatchListJobDetailsRequest;
import com.huaweicloud.sdk.drs.v3.model.BatchListJobDetailsResponse;
import com.huaweicloud.sdk.drs.v3.model.BatchListJobStatusRequest;
import com.huaweicloud.sdk.drs.v3.model.BatchListJobStatusResponse;
import com.huaweicloud.sdk.drs.v3.model.BatchListProgressesRequest;
import com.huaweicloud.sdk.drs.v3.model.BatchListProgressesResponse;
import com.huaweicloud.sdk.drs.v3.model.BatchPauseJobReq;
import com.huaweicloud.sdk.drs.v3.model.BatchQueryJobReqPage;
import com.huaweicloud.sdk.drs.v3.model.BatchQueryProgressReq;
import com.huaweicloud.sdk.drs.v3.model.BatchRestoreTaskRequest;
import com.huaweicloud.sdk.drs.v3.model.BatchRestoreTaskResponse;
import com.huaweicloud.sdk.drs.v3.model.BatchRetryReq;
import com.huaweicloud.sdk.drs.v3.model.BatchStopJobsRequest;
import com.huaweicloud.sdk.drs.v3.model.BatchStopJobsResponse;
import com.huaweicloud.sdk.drs.v3.model.JobInfo;
import com.huaweicloud.sdk.drs.v3.model.PageReq;
import com.huaweicloud.sdk.drs.v3.model.PauseInfo;
import com.huaweicloud.sdk.drs.v3.model.QueryJobResp;
import com.huaweicloud.sdk.drs.v3.model.QueryJobsReq;
import com.huaweicloud.sdk.drs.v3.model.RetryInfo;
import com.huaweicloud.sdk.drs.v3.model.ShowJobListRequest;
import com.huaweicloud.sdk.drs.v3.model.ShowJobListResponse;
import com.huaweicloud.sdk.drs.v3.region.DrsRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.huaweicloud.sdk.drs.v3.model.QueryJobsReq.DbUseTypeEnum.SYNC;
import static com.huaweicloud.sdk.drs.v3.model.QueryJobsReq.EngineTypeEnum.MYSQL;
import static com.huaweicloud.sdk.drs.v3.model.QueryJobsReq.NetTypeEnum.EIP;
import static com.huaweicloud.sdk.drs.v3.model.QueryJobsReq.StatusEnum.CONFIGURATION;
import static com.huaweicloud.sdk.drs.v3.model.ShowJobListRequest.XLanguageEnum.EN_US;

public class PauseAndRetryJobDemo {
    private static final Logger logger = LoggerFactory.getLogger(PauseAndRetryJobDemo.class.getName());

    public static void main(String[] args) throws InterruptedException {
        // 创建认证
        String ak = "<YOUR AK>";
        String sk = "<YOUR SK>";

        ICredential auth = new BasicCredentials().withAk(ak).withSk(sk);
        // 配置客户端属性
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);
        // 创建DrsClient实例
        DrsClient client = DrsClient.newBuilder().withCredential(auth).withHttpConfig(config)
                .withRegion(DrsRegion.CN_NORTH_4).build();
        // 查询租户任务列表
        List<JobInfo> jobInfos = showJobList(client);
        if (jobInfos == null || jobInfos.size() == 0) {
            return;
        }
        // 批量查询任务详情
        List<QueryJobResp> queryJobRespList = batchListJobDetails(client);
        if (queryJobRespList == null || queryJobRespList.size() == 0) {
            return;
        }
        // 暂停任务
        if (pauseJobFail(client)) {
            return;
        }
        String status = getStatus(client);
        // 任务状态为暂停中时，后续可根据需要续传
        retryJob(client, status);
        // 批量查询任务进度
        batchListProgresses(client);
    }

    /**
     * 查询租户任务列表
     *
     * @param client
     * @return
     */
    private static List<JobInfo> showJobList(DrsClient client) {
        ShowJobListRequest request = new ShowJobListRequest();
        QueryJobsReq queryJobsReq = new QueryJobsReq();
        // 名称或ID，选填
        queryJobsReq.setName("<YOUR JOB NAME OR JOB id>");
        // 引擎类型，选填
        queryJobsReq.setEngineType(MYSQL);
        // 任务类型，选填
        queryJobsReq.setDbUseType(SYNC);
        // 企业项目，选填
        queryJobsReq.setEnterpriseProjectId("<YOUR JOB ENTERPRISE PROJECT ID>");
        // 网络类型，选填
        queryJobsReq.setNetType(EIP);
        // 服务名称，选填
        queryJobsReq.setServiceName("<YOUR SERVICE NAME>");
        // 状态，选填
        queryJobsReq.setStatus(CONFIGURATION);
        //标签，选填
        Map<String, String> tags = new HashMap<>();
        queryJobsReq.setTags(tags);
        // 每页记录数，选填， 默认10
        queryJobsReq.setPerPage(10);
        // 第几页，选填，默认1
        queryJobsReq.setCurPage(1);
        request.setBody(queryJobsReq);
        request.setXLanguage(EN_US);
        ShowJobListResponse showJobListResponse = client.showJobList(request);
        logger.info(JsonUtils.toJSON(showJobListResponse));
        return showJobListResponse.getJobs();
    }

    /**
     * 批量查询任务详情
     *
     * @param client
     * @return
     */
    private static List<QueryJobResp> batchListJobDetails(DrsClient client) {
        BatchListJobDetailsRequest batchListJobDetailsRequest = new BatchListJobDetailsRequest();
        BatchQueryJobReqPage batchQueryJobReqPage = new BatchQueryJobReqPage();
        // 批量查询任务信息任务ID请求列表
        List<String> jobs = new ArrayList<>();
        jobs.add("<YOUR JOB ID>");
        batchQueryJobReqPage.setJobs(jobs);
        // 分页请求体
        PageReq pageReq = new PageReq();
        // 当前页，选填，默认1
        pageReq.setCurPage(1);
        // 每页显示项数，选填，默认5
        pageReq.setPerPage(5);
        batchQueryJobReqPage.setPageReq(pageReq);
        batchListJobDetailsRequest.setBody(batchQueryJobReqPage);
        BatchListJobDetailsResponse batchListJobDetailsResponse = client.batchListJobDetails(batchListJobDetailsRequest);
        logger.info(JsonUtils.toJSON(batchListJobDetailsResponse));
        return batchListJobDetailsResponse.getResults();
    }

    /**
     * 暂停任务
     *
     * @param client
     * @return
     */
    private static boolean pauseJobFail(DrsClient client) {
        BatchStopJobsRequest batchStopJobsRequest = new BatchStopJobsRequest();
        BatchPauseJobReq batchPauseJobReq = new BatchPauseJobReq();
        List<PauseInfo> jobs = new ArrayList<>();
        PauseInfo pauseInfo = new PauseInfo();
        pauseInfo.withJobId("<YOUR JOB ID>");
        pauseInfo.withPauseMode(PauseInfo.PauseModeEnum.TARGET);
        jobs.add(pauseInfo);
        batchPauseJobReq.withJobs(jobs);
        batchStopJobsRequest.withBody(batchPauseJobReq);
        BatchStopJobsResponse batchStopJobsResponse = client.batchStopJobs(batchStopJobsRequest);
        logger.info(batchStopJobsResponse.toString());
        if (batchStopJobsResponse.getHttpStatusCode() != 200) {
            logger.error(batchStopJobsResponse.toString());
            return true;
        }
        return false;
    }

    /**
     * 续传任务
     *
     * @param client
     */
    private static void retryJob(DrsClient client, String status) throws InterruptedException {
        while (!"PAUSING".equals(status)) {
            TimeUnit.SECONDS.sleep(20);
            status = getStatus(client);
        }
        BatchRestoreTaskRequest batchRestoreTaskRequest = new BatchRestoreTaskRequest();
        BatchRetryReq batchRetryReq = new BatchRetryReq();
        List<RetryInfo> retryInfos = new ArrayList<>();
        RetryInfo retryInfo = new RetryInfo();
        retryInfo.withJobId("<YOUR JOB ID>");
        retryInfos.add(retryInfo);
        batchRetryReq.withJobs(retryInfos);
        batchRestoreTaskRequest.withBody(batchRetryReq);
        BatchRestoreTaskResponse batchRestoreTaskResponse = client.batchRestoreTask(batchRestoreTaskRequest);
        logger.info(batchRestoreTaskResponse.toString());
    }

    /**
     * 获取任务状态
     *
     * @param client
     * @return
     */
    private static String getStatus(DrsClient client) {
        BatchListJobStatusRequest batchListProgressesRequest = new BatchListJobStatusRequest();
        BatchQueryJobReqPage batchQueryJobReqPage = new BatchQueryJobReqPage();
        List<String> jobs = new ArrayList<>();
        jobs.add("<YOUR JOB ID>");
        batchQueryJobReqPage.withJobs(jobs);
        batchListProgressesRequest.setBody(batchQueryJobReqPage);
        BatchListJobStatusResponse batchListJobStatusResponse = client.batchListJobStatus(batchListProgressesRequest);
        return batchListJobStatusResponse.getResults().get(0).getStatus().getValue();
    }

    /**
     * 批量查询任务进度
     *
     * @param client
     * @return
     */
    private static void batchListProgresses(DrsClient client) {
        BatchListProgressesRequest batchListProgressesRequest = new BatchListProgressesRequest();
        BatchQueryProgressReq batchQueryJobReqPage = new BatchQueryProgressReq();
        List<String> jobIds = new ArrayList<>();
        jobIds.add("<YOUR JOB ID>");
        batchQueryJobReqPage.withJobs(jobIds);
        batchListProgressesRequest.setBody(batchQueryJobReqPage);
        BatchListProgressesResponse batchListProgressesResponse = client.batchListProgresses(batchListProgressesRequest);
        logger.info(batchListProgressesResponse.toString());
    }
}